<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Historywarn;
use DB;

class WarnHistory extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'warn:history {time} {cid} {sid} {--day=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'wanr history';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $time = $this->argument('time');
        $cid = $this->argument('cid');
        $sid = $this->argument('sid');
        if(!$cid) {
            $this->error('device cid is required!');
        }
        if(!$sid) {
            $this->error('device sid is required!');
        }
        if(!$time) {
            $this->error('device time is required!');
        }
        $device = Historywarn::orderBy('rs_updatetime', 'desc')->limit(10)->get()->toArray();
      //  $data=[];
        $optionDay = $this->option('day');
        $times = [];
        if($optionDay) {
            $days = range(1, $optionDay);
            foreach ($days as $v) {
                $subDays = $v-1;
                $times[] = date('Y-m-d', strtotime("-{$subDays} day"));
            }
        }else{
            $times[] = $time;
        }
        $data = [];
        foreach ($times as $vtime) {
            foreach ($device as &$v) {
                $v['Co_ID'] = $cid;
                $v['Fid'] = $sid;
                $v['rs_updatetime'] = preg_replace('/^\d{4}-\d{2}-\d{2}/', $vtime, $v['rs_updatetime']);
                unset($v['hw_index']);
                $data[] = $v;
            }
        }

        
        Historywarn::unguard();
        DB::table('t_historywarn')->insert($data);
    }
}
